package com.paiai.lslease.service.apphouse;

import com.paiai.lslease.auto.dao.AppSocketDAO;
import com.paiai.lslease.auto.model.AppSocket;
import com.paiai.lslease.auto.model.AppSocketExample;
import com.paiai.lslease.dao.apphouse.AppSocketInfoDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

public class AppSocketServiceImpl implements AppSocketService {
    private static final Logger logger = LoggerFactory.getLogger(AppSocketServiceImpl.class);

    private AppSocketDAO appSocketDAO;
    private AppSocketInfoDAO appSocketInfoDAO;
    private AppHouseService appHouseService;

    public void setAppSocketDAO(AppSocketDAO appSocketDAO) {
        this.appSocketDAO = appSocketDAO;
    }

    public void setAppSocketInfoDAO(AppSocketInfoDAO appSocketInfoDAO) {
        this.appSocketInfoDAO = appSocketInfoDAO;
    }

    public void setAppHouseService(AppHouseService appHouseService) {
        this.appHouseService = appHouseService;
    }

    public AppSocket insertSocket(AppSocket appSocket) throws Exception {
        //默认所有用户都能添加插座
//        //检测当前插座关联的房源是否存在
//        if (!appHouseService.checkHouseExist(appSocket.getHouseId())) {
//            logger.info("当前插座关联的房源不存在");
//            return null;
//        }
        appSocketDAO.insert(appSocket);
        return selectSocket(appSocketInfoDAO.selectNeweastAppSocketId());
    }

    public boolean deleteSocket(int socketId) throws Exception {
        if (!checkSocketExist(socketId)) {
            return true;
        }
        AppSocket appSocket = new AppSocket();
        appSocket.setId(socketId);
        appSocket.setItem1("-1");
        appSocket.setUpdateTime(new Date());
        return appSocketDAO.updateByPrimaryKeySelective(appSocket) > 0;
    }

    public AppSocket modifySocket(AppSocket appSocket) throws Exception {
        if (appSocketDAO.updateByPrimaryKeySelective(appSocket) <= 0) {
            return null;
        }
        return selectSocket(appSocket.getId());
    }

    public List<AppSocket> selectAllSocket(int operateUserId) throws Exception {
        AppSocketExample appSocketExample = new AppSocketExample();
        appSocketExample.createCriteria().andManageUserIdEqualTo(operateUserId).andItem1EqualTo("1");
        return appSocketDAO.selectByExample(appSocketExample);
    }

    public AppSocket selectSocket(int socketId) throws Exception {
        AppSocket appSocket = appSocketDAO.selectByPrimaryKey(socketId);
        return appSocket != null && "1".equalsIgnoreCase(appSocket.getItem1()) ? appSocket : null;
    }

    public boolean checkSocketExist(int socketId) throws Exception {
        return selectSocket(socketId) != null;
    }
}
